from isapi import isapicon
from isapi.simple import SimpleExtension
import sys, os, stat

if hasattr(sys, "isapidllhandle"):
    import win32traceutil
import scgi
from isapi import InternalReloadException
import win32event, win32file, winerror, win32con, threading
from isapi import threaded_extension


class Extension(threaded_extension.ThreadPoolExtension):
    """pyISAPI_SCGI ISAPIExtension ver 0.0.2"""

    def Dispatch(self,ecb):
        scgi.handler(ecb)

    def TerminateExtension(self,status):
        threaded_extension.ThreadPoolExtension.TerminateExtension(self,status)
        scgi.terminate()



# The entry points for the ISAPI extension.
def __ExtensionFactory__():
	return Extension()

# Our special command line customization.
# Pre-install hook for our virtual directory.
def PreInstallDirectory(params, options):
    # If the user used our special '--description' option,
    # then we override our default.
    if options.description:
        params.Description = options.description

# Post install hook for our entire script
def PostInstall(params, options):
    print ""
    print "The sample has been installed."
    print "Point your browser to /AdvancedPythonSample"
    print "If you modify the source file and reload the page,"
    print "you should see the reload counter increment"

# Handler for our custom 'status' argument.
def status_handler(options, log, arg):
    "Query the status of something"
    print "Everything seems to be fine!"

custom_arg_handlers = {"status": status_handler}

if __name__=='__main__':
    # If run from the command-line, install ourselves.
    from isapi.install import *
    params = ISAPIParameters()
    # Setup the virtual directories - this is a list of directories our
    # extension uses - in this case only 1.
    # Each extension has a "script map" - this is the mapping of ISAPI
    # extensions.
    sm = [
        ScriptMapParams(Extension="*", Flags=0)
    ]
    vd = VirtualDirParameters(Name="pyISAPI_SCGI",
                              Description = Extension.__doc__,
                              ScriptMaps = sm,
                              ScriptMapUpdate = "replace",
                              # specify the pre-install hook.
                              PreInstall = PreInstallDirectory
                              )
    params.VirtualDirs = [vd]
    # Setup our custom option parser.
    from optparse import OptionParser
    parser = OptionParser('') # black usage, so isapi sets it.
    parser.add_option("", "--description",
                      action="store",
                      help="custom description to use for the virtual directory")
    
    HandleCommandLine(params, opt_parser=parser, 
                              custom_arg_handlers = custom_arg_handlers)
